import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';
import _slicedToArray from '@babel/runtime/helpers/esm/slicedToArray';
import _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray';
import { useCallback, useMemo, useState } from 'react';
/**
 * 持有父节点引用
 * @param nodes
 * @param parent
 */
var traverse = function traverse(nodes, parent) {
  return (nodes || []).map(function (node, index) {
    var prefix =
      parent && parent.childFieldNamePrefix
        ? [].concat(_toConsumableArray(parent.childFieldNamePrefix), [index])
        : [index];
    var convertedNode = _objectSpread(
      _objectSpread({}, node),
      {},
      {
        _parent: parent,
        fieldNamePrefix: prefix,
        childFieldNamePrefix: [].concat(_toConsumableArray(prefix), ['children']),
      },
    );
    return _objectSpread(
      _objectSpread({}, convertedNode),
      {},
      {
        children: convertedNode.children
          ? traverse(convertedNode.children, convertedNode)
          : undefined,
      },
    );
  });
};
export default function useTable(_ref) {
  var value = _ref.value,
    uniqueKey = _ref.uniqueKey,
    rowKeyProp = _ref.rowKey;
  var dataSource = useMemo(
    function () {
      return value ? traverse(value, null) : [];
    },
    [value],
  );
  var _useState = useState({
      current: 1,
      pageSize: 10,
    }),
    _useState2 = _slicedToArray(_useState, 2),
    pagination = _useState2[0],
    setPagination = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    expandedKeys = _useState4[0],
    setExpandedKeys = _useState4[1];
  var rowKey = useMemo(
    function () {
      return typeof rowKeyProp === 'function'
        ? rowKeyProp
        : function (row) {
            return row[uniqueKey] || row._vid;
          };
    },
    [rowKeyProp, uniqueKey],
  );
  var expandRow = useCallback(
    function (expanded, row) {
      var result = _toConsumableArray(expandedKeys);
      var key = rowKey(row);
      if (expanded) {
        // @ts-ignore
        if (!result.includes(key)) result.push(key);
      } else {
        result = result.filter(function (k) {
          return k !== key;
        });
      }
      setExpandedKeys(result);
    },
    [expandedKeys, rowKey],
  );
  return {
    dataSource: dataSource,
    rowKey: rowKey,
    pagination: pagination,
    setPagination: setPagination,
    expandedKeys: expandedKeys,
    onExpand: expandRow,
    expandRow: expandRow,
  };
}
